package cn.xz.mxxz.net

import android.os.Handler
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import cn.xz.mxxz.base.BaseApplication
import cn.xz.mxxz.bean.*
import cn.xz.mxxz.dialog.AllNowDialog
import cn.xz.mxxz.util.EventBusUtils
import cn.xz.mxxz.util.SendTcpUtils
import cn.xz.mxxz.util.SessionUtils
import cn.xz.mxxz.util.ZhuanHuan
import java.io.IOException
import java.util.*

/**
 * 设备管理
 * */
object ControlDevice {

    //获取对应设备
    fun getThisDevice(tag: Int): DeviceList?{
        var mD: DeviceList? = null
        //设备
        val deviceList = SessionUtils.getDataList(CommonLib.Device_CACHE,DeviceList::class.java)
        if (deviceList.isNotEmpty()){
            deviceList.forEach {
                if (it.id == tag){
                    mD = it
                }
            }
        }
        return mD
    }

    //获取对应设备名称
    fun getDeviceName(tag: Int): String{
        val mD = ControlDevice.getThisDevice(tag)
        var mS = ""
        if (mD != null){
            mS = mD.name
        }
        return mS
    }

    //全开
    fun openAll(){
        //当前进行的个数
        var closeIndexCount = 0L
        //延迟计算的个数，用于弹窗显示
        var closeDCount = 0
        //设备
        val deviceList = SessionUtils.getDataList(CommonLib.Device_CACHE, DeviceList::class.java)
        //灯光
        val lightList = SessionUtils.getDataList(CommonLib.Light_CACHE,LightList::class.java)
        if (deviceList.size + lightList.size > 0){
            //显示进行中弹窗
            AllNowDialog.newInstance(deviceList.size + lightList.size).show((BaseApplication.getCurrentActivity() as AppCompatActivity).supportFragmentManager,"AllNowDialog91")

            if (deviceList.isNotEmpty()){
                deviceList.forEach {
                    //延迟
                    Handler().postDelayed({
                        openDevice(it)
                        //发通知显示文案
                        closeDCount ++
                        EventBusUtils.postEvent(
                            EventBusMessage(AllNowDialog.isOpen,
                                AlLNowData(it.name,closeDCount)
                            )
                        )
                    }, closeIndexCount * 1000)
                    closeIndexCount ++
                }
            }
            if (lightList.isNotEmpty()){
                lightList.forEach {
                    //延迟
                    Handler().postDelayed({
                        openLight(it)
                        closeDCount ++
                        EventBusUtils.postEvent(EventBusMessage(AllNowDialog.isOpen,
                            AlLNowData(it.name,closeDCount)
                        ))
                    }, closeIndexCount * 1000)
                    closeIndexCount ++
                }
            }
        }
    }

    //全关
    fun closeAll(){
        //当前进行的个数
        var closeIndexCount = 0L
        //延迟计算的个数，用于弹窗显示
        var closeDCount = 0
        //设备
        val deviceList = SessionUtils.getDataList(CommonLib.Device_CACHE,DeviceList::class.java)
        //灯光
        val lightList = SessionUtils.getDataList(CommonLib.Light_CACHE,LightList::class.java)
        if (deviceList.size + lightList.size > 0){
            //显示进行中弹窗
            AllNowDialog.newInstance(deviceList.size + lightList.size).show((BaseApplication.getCurrentActivity() as AppCompatActivity).supportFragmentManager,"AllNowDialog1")

            if (deviceList.isNotEmpty()){
                deviceList.forEach {
                    //延迟
                    Handler().postDelayed({
                        //开合屏不关
                        if (it.ip != "192.168.10.17" && it.ip != "192.168.10.16"){
                            closeDevice(it)
                        }
                        //发通知显示文案
                        closeDCount ++
                        EventBusUtils.postEvent(EventBusMessage(AllNowDialog.isClose,
                            AlLNowData(it.name,closeDCount)
                        ))
                    }, closeIndexCount * 1000)
                    closeIndexCount ++
                }
            }
            //灯光
            if (lightList.isNotEmpty()){
                lightList.forEach {
                    //延迟
                    Handler().postDelayed({
                        closeLight(it)
                        closeDCount ++
                        EventBusUtils.postEvent(EventBusMessage(AllNowDialog.isClose,
                            AlLNowData(it.name,closeDCount)
                        ))
                    }, closeIndexCount * 1000)
                    closeIndexCount ++
                }
            }
        }
    }


    //灯光全开
    interface OpenLightListener { //回调，全部开完后在进行操作
        fun over()
    }
    fun openAllLight(l: OpenLightListener){
        //当前进行的个数
        var closeIndexCount = 0L
        //延迟计算的个数，用于弹窗显示
        var closeDCount = 0
        //灯光
        val lightList = SessionUtils.getDataList(CommonLib.Light_CACHE,LightList::class.java)
        if (lightList.size > 0){
            //显示进行中弹窗
            AllNowDialog.newInstance(lightList.size).show((BaseApplication.getCurrentActivity() as AppCompatActivity).supportFragmentManager,"AllNowDialog13")
            lightList.forEach {
                //延迟
                Handler().postDelayed({
                    openLight(it)
                    closeDCount ++
                    EventBusUtils.postEvent(EventBusMessage(AllNowDialog.isOpen,
                        AlLNowData(it.name,closeDCount)
                    ))
                    if(closeDCount == lightList.size){
                        l.over()
                    }
                }, closeIndexCount * 1000)
                closeIndexCount ++
            }
        }
    }

    //灯光全关
    interface CloseLightListener { //回调，全部关闭后在进行操作
        fun over()
    }
    fun closeAllLight(l: CloseLightListener){
        //当前进行的个数
        var closeIndexCount = 0L
        //延迟计算的个数，用于弹窗显示
        var closeDCount = 0
        //灯光
        val lightList = SessionUtils.getDataList(CommonLib.Light_CACHE,LightList::class.java)
        if (lightList.size > 0){
            //显示进行中弹窗
            AllNowDialog.newInstance(lightList.size).show((BaseApplication.getCurrentActivity() as AppCompatActivity).supportFragmentManager,"AllNowDialog14")
            //灯光
            lightList.forEach {
                //延迟
                Handler().postDelayed({
                    closeLight(it)
                    closeDCount ++
                    EventBusUtils.postEvent(EventBusMessage(AllNowDialog.isClose,
                        AlLNowData(it.name,closeDCount)
                    ))
                    if(closeDCount == lightList.size){
                        l.over()
                    }}, closeIndexCount * 1000)
                closeIndexCount ++
            }
        }
    }

    //设备全开
    interface OpenDeviceListener { //回调，全部开完后在进行操作
        fun over()
    }
    fun openAllDevice(l: OpenDeviceListener){
        //当前进行的个数
        var closeIndexCount = 0L
        //延迟计算的个数，用于弹窗显示
        var closeDCount = 0
        //设备
        val deviceList = SessionUtils.getDataList(CommonLib.Device_CACHE, DeviceList::class.java)
        if (deviceList.size > 0){
            //显示进行中弹窗
            AllNowDialog.newInstance(deviceList.size).show((BaseApplication.getCurrentActivity() as AppCompatActivity).supportFragmentManager,"AllNowDialog100")
            deviceList.forEach {
                    //延迟
                    Handler().postDelayed({
                        openDevice(it)
                        //发通知显示文案
                        closeDCount ++
                        EventBusUtils.postEvent(
                            EventBusMessage(AllNowDialog.isOpen,
                                AlLNowData(it.name,closeDCount)
                            )
                        )
                        if(closeDCount == deviceList.size){
                            l.over()
                        }
                    }, closeIndexCount * 1000)
                    closeIndexCount ++
            }
        }
    }

    //设备全关
    interface CloseDeviceListener { //回调，全部关完后在进行操作
        fun over()
    }
    fun closeAllDevice(l: CloseDeviceListener){
        //当前进行的个数
        var closeIndexCount = 0L
        //延迟计算的个数，用于弹窗显示
        var closeDCount = 0
        //设备
        val deviceList = SessionUtils.getDataList(CommonLib.Device_CACHE,DeviceList::class.java)
        if (deviceList.size > 0){
            //显示进行中弹窗
            AllNowDialog.newInstance(deviceList.size).show((BaseApplication.getCurrentActivity() as AppCompatActivity).supportFragmentManager,"AllNowDialog1")
             deviceList.forEach {
                    //延迟
                    Handler().postDelayed({
                        //开合屏不关
                        if (it.ip != "192.168.10.17" && it.ip != "192.168.10.16"){
                            closeDevice(it)
                        }
                        //发通知显示文案
                        closeDCount ++
                        EventBusUtils.postEvent(EventBusMessage(AllNowDialog.isClose,
                            AlLNowData(it.name,closeDCount)
                        ))
                        if(closeDCount == deviceList.size){
                            l.over()
                        }
                    }, closeIndexCount * 1000)
                    closeIndexCount ++
             }
        }
    }

    //开启指定设备
    fun openThisDevice(target: Int){
        //设备
        val deviceList = SessionUtils.getDataList(CommonLib.Device_CACHE,DeviceList::class.java)
        if (deviceList.isNotEmpty()){
            deviceList.forEach {
                if (it.id == target){
                    openDevice(it)
                }
            }
        }
    }

    //关闭指定设备
    fun closeThisDevice(target: Int){
        //设备
        val deviceList = SessionUtils.getDataList(CommonLib.Device_CACHE,DeviceList::class.java)
        if (deviceList.isNotEmpty()){
            deviceList.forEach {
                if (it.id == target){
                    closeDevice(it)
                }
            }
        }
    }

    //开启指定灯光
    fun openThisLight(target: Int){
        val lightList = SessionUtils.getDataList(CommonLib.Light_CACHE,LightList::class.java)
        if (lightList.isNotEmpty()){
            lightList.forEach {
                if (it.id == target){
                    openLight(it)
                }
            }
        }
    }

    //关闭指定灯光
    fun closeThisLight(target: Int){
        val lightList = SessionUtils.getDataList(CommonLib.Light_CACHE,LightList::class.java)
        if (lightList.isNotEmpty()){
            lightList.forEach {
                if (it.id == target){
                    closeLight(it)
                }
            }
        }
    }

    //开启设备
    fun openDevice(d: DeviceList){
        //设备分类
        when(d.deviceType){
            1,3,13->{
               openLight(d)
            }
            2->{
                openPC(d)
            }
            4,5,8,10->{
                openProjector(d)
            }
            9->{
                openClickPC(d)
            }
            11->{
                openPCBox(d)
            }
        }

    }

    //关闭设备
    fun closeDevice(d: DeviceList){
        when(d.deviceType){
            1->{
                closeLight(d)
            }
            2,3,9,11,13->{
                closePC(d)
            }
            4,5,8,10->{
                closeProjector(d)
            }
        }
    }


    //开启灯光
    fun openLight(lightList: LightList){
        try {
            val packet = byteArrayOf(0x55.toByte(), 0x01.toByte(), 0x12.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x01.toByte(), 0x69.toByte())
            packet[1] = lightList.switchGroup.toByte()
            packet[6] = (packet[6] + (lightList.switchIndex - 1).toByte()).toByte()
            packet[7] = (packet[7] + (lightList.switchIndex - 1 + lightList.switchGroup - 1).toByte()).toByte()
            SendTcpUtils.service(packet, lightList.switchIP, lightList.switchPort,lightList.com)
        }catch (e: Exception){
            e.printStackTrace()
        }
    }
    private fun openLight(deviceList: DeviceList) {
        val packet = byteArrayOf(0x55.toByte(), 0x01.toByte(), 0x12.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x01.toByte(), 0x69.toByte())
        packet[1] = deviceList.switchGroup.toByte()
        packet[6] = (packet[6] + (deviceList.switchIndex - 1).toByte()).toByte()
        packet[7] = (packet[7] + (deviceList.switchIndex - 1 + deviceList.switchGroup - 1).toByte()).toByte()
        SendTcpUtils.service(packet, deviceList.switchIP, deviceList.switchPort,deviceList.com)
    }

    //关闭灯光
    fun closeLight(lightList: LightList){
        try {
            val packet = byteArrayOf(0x55.toByte(), 0x01.toByte(), 0x11.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x01.toByte(), 0x68.toByte())
            packet[1] = lightList.switchGroup.toByte()
            packet[6] = (packet[6] + (lightList.switchIndex - 1).toByte()).toByte()
            packet[7] = (packet[7] + (lightList.switchIndex - 1 + lightList.switchGroup - 1).toByte()).toByte()
            SendTcpUtils.service(packet, lightList.switchIP, lightList.switchPort,lightList.com)
        }catch (e: Exception){
            e.printStackTrace()
        }
    }
    private fun closeLight(deviceList: DeviceList) {
        val packet = byteArrayOf(0x55.toByte(), 0x01.toByte(), 0x11.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x01.toByte(), 0x68.toByte())
        packet[1] = deviceList.switchGroup.toByte()
        packet[6] = (packet[6] + (deviceList.switchIndex - 1).toByte()).toByte()
        packet[7] = (packet[7] + (deviceList.switchIndex - 1 + deviceList.switchGroup - 1).toByte()).toByte()
        Log.e("debug-->closeloght:", ZhuanHuan.bytesToHexString(packet))
        SendTcpUtils.service(packet, deviceList.switchIP, deviceList.switchPort,deviceList.com)
    }


    private fun openPC(deviceList: DeviceList) {
        val remoteWake = RemoteWake()
        remoteWake.openPC(deviceList.mac, remoteWake)
    }

    private fun closePC(deviceList: DeviceList) {
        val ip = deviceList.ip
        OkHttpUtil.post("http://" + ip + ":8088/?act=shutdown&object=&states=0&r=" + (Math.random() * 10000).toInt())
    }

    fun restartPC(ip: String) {
        OkHttpUtil.post("http://" + ip + ":8088/?act=restart&object=&states=0&r=" + (Math.random() * 10000).toInt())
    }

    private fun openProjector(deviceList: DeviceList) {
        val protocol = deviceList.protocol
        val closeProtocol = deviceList.closeProtocol
        val openProtocol = deviceList.openProtocol
        val ip = deviceList.ip
        val port = deviceList.port
        val charType = deviceList.charType
        Log.e("debug-->openProjector:", openProtocol + "charType:" + charType)
        if (deviceList.deviceType === 10) {
            //25 31 50 4f 57 52 20 31 0d
            val sendOpen = byteArrayOf(0x25, 0x31, 0x50, 0x4f.toByte(), 0x57, 0x52, 0x20, 0x31, 0x0d.toByte())
            SendTcpUtils.service(sendOpen, ip, port,deviceList.com)
            return
        }
        if (protocol == 0) {
            //tcp
            if (charType == 0) {
                SendTcpUtils.service(ZhuanHuan.hexStringToBytes(openProtocol), ip, port,deviceList.com)
            } else if (charType == 1) {
                SendTcpUtils.service(openProtocol.toByteArray(), ip, port,deviceList.com)
            } else {
                SendTcpUtils.service(ZhuanHuan.hexStringToBytes(openProtocol), ip, port,deviceList.com)
            }
        } else if (protocol == 1) {
            SendUdp.send(openProtocol, ip, port)
        } else if (protocol == 2) {
            OkHttpUtil.post("http:$ip:$port?$openProtocol")
        }
    }


    private fun closeProjector(deviceList: DeviceList) {
        val protocol = deviceList.protocol
        val closeProtocol = deviceList.closeProtocol
        val openProtocol = deviceList.openProtocol
        val ip = deviceList.ip
        val port = deviceList.port
        val charType = deviceList.charType
        Log.e("debug-->closeProjector:", closeProtocol + "charType:" + charType)
        if (deviceList.deviceType === 10) {
            //25 31 50 4f 57 52 20 30 0d
            val sendOpen = byteArrayOf(0x25, 0x31, 0x50, 0x4f.toByte(), 0x57, 0x52, 0x20, 0x30, 0x0d.toByte())
            SendTcpUtils.service(sendOpen, ip, port,deviceList.com)
            return
        }
        if (protocol == 0) {
            //tcp
            if (charType == 0) {
                SendTcpUtils.service(ZhuanHuan.hexStringToBytes(closeProtocol), ip, port,deviceList.com)
            } else if (charType == 1) {
                SendTcpUtils.service(closeProtocol.toByteArray(), ip, port,deviceList.com)
            } else {
                SendTcpUtils.service(ZhuanHuan.hexStringToBytes(closeProtocol), ip, port,deviceList.com)
            }
        } else if (protocol == 1) {
            SendUdp.send(closeProtocol, ip, port)
        } else if (protocol == 2) {
            OkHttpUtil.post("http://$ip:$port?$closeProtocol")
        }
    }

    private fun openClickPC(deviceList: DeviceList) {
        val sendOpen = byteArrayOf(0x55, 0x01, 0x21, 0x00, 0x00, 0x64, 0x01, 0xDC.toByte())
        sendOpen[1] = deviceList.switchGroup.toByte()
        sendOpen[6] = (sendOpen[6] + (deviceList.switchIndex - 1).toByte()).toByte()
        sendOpen[7] = (sendOpen[7] + (deviceList.switchIndex - 1 + deviceList.switchGroup - 1).toByte()).toByte()
        var mNetClient: NetClient? = null
        Log.e("debug-->sendOpen:", Arrays.toString(sendOpen))
        try {
            if (mNetClient == null) {
                mNetClient = NetClient()
                mNetClient.initSocket(deviceList.switchIP, deviceList.switchPort)
                mNetClient.execute(sendOpen)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun openPCBox(deviceList: DeviceList?) {
        if (deviceList == null) {
            return
        }
        val ip = deviceList.switchIP
        val port = deviceList.switchPort
        val index = deviceList.switchIndex
        val sendMsg = "OPEN$index"
        SendTcpUtils.service(sendMsg.toByteArray(), ip, port,deviceList.com)
    }


    //组合字符串数组
    fun addArray(buffer: ByteArray, buffer1: ByteArray): ByteArray {
        val newArr = ByteArray(buffer.size + buffer1.size)
        for (i in buffer.indices) {
            newArr[i] = buffer[i]
        }
        for (j in buffer1.indices) {
            newArr[buffer.size + j] = buffer1[j]
        }
        return newArr
    }

}